const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    id: null,
    form: {
      product_id: '',
      name: '',
      model_code: '',
      fabric_color: '',
      description: '',
      status: 1
    },
    productIndex: 0,
    statusIndex: 0,
    productOptions: [{ id: '', name: '请选择产品' }],
    statusOptions: ['禁用', '启用'],
    loading: false
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/product-model-detail/product-model-detail')) {
      return
    }
    
    this.loadProducts()
    if (options.id) {
      this.setData({
        id: options.id
      })
      this.loadData()
    }
  },

  async loadProducts() {
    try {
      const res = await api.getProductList({
        status: 1
      })

      if (res.code === 1) {
        const products = res.data.list.map(item => ({
          id: item.id,
          name: item.name
        }))
        
        this.setData({
          productOptions: [{ id: '', name: '请选择产品' }, ...products]
        })
      }
    } catch (error) {
      console.error('加载产品列表失败:', error)
    }
  },

  async loadData() {
    try {
      const res = await api.getProductModelList({
        id: this.data.id
      })

      if (res.code === 1 && res.data.list.length > 0) {
        const item = res.data.list[0]
        console.log('获取到的型号数据:', item)
        console.log('产品信息:', item.product)
        
        // 查找产品在产品选项中的索引
        let productIndex = 0
        if (item.product && item.product.id) {
          productIndex = this.data.productOptions.findIndex(p => p.id == item.product.id)
          if (productIndex === -1) {
            productIndex = 0
          }
        }
        
        this.setData({
          form: {
            product_id: item.product_id,
            name: item.name,
            model_code: item.model_code || '',
            fabric_color: item.fabric_color || '',
            description: item.description || '',
            status: item.status
          },
          productIndex: productIndex,
          statusIndex: item.status === 1 ? 1 : 0
        })
        
        // 如果产品信息不在选项中，添加到选项中
        if (item.product && item.product.id && productIndex === 0) {
          const newProduct = {
            id: item.product.id,
            name: item.product.name
          }
          const newProductOptions = [this.data.productOptions[0], newProduct, ...this.data.productOptions.slice(1)]
          this.setData({
            productOptions: newProductOptions,
            productIndex: 1
          })
        }
      }
    } catch (error) {
      console.error('加载型号详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  onProductChange(e) {
    const index = parseInt(e.detail.value)
    this.setData({
      productIndex: index,
      'form.product_id': this.data.productOptions[index].id
    })
  },

  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value),
      'form.status': parseInt(e.detail.value)
    })
  },

  async onSubmit(e) {
    if (this.data.loading) return

    // 检查权限
    const action = this.data.id ? 'edit' : 'add'
    if (!this.hasPermission('model_manage', action)) {
      wx.showToast({
        title: `您没有${this.data.id ? '编辑' : '新增'}权限`,
        icon: 'none'
      })
      return
    }

    const formData = e.detail.value
    
    if (!formData.name.trim()) {
      wx.showToast({
        title: '请输入型号名称',
        icon: 'none'
      })
      return
    }

    if (!this.data.form.product_id) {
      wx.showToast({
        title: '请选择所属产品',
        icon: 'none'
      })
      return
    }

    this.setData({ loading: true })

    try {
      const data = {
        product_id: this.data.form.product_id,
        name: formData.name.trim(),
        model_code: formData.model_code.trim(),
        fabric_color: formData.fabric_color.trim(),
        description: formData.description.trim(),
        status: this.data.form.status
      }

      let res
      if (this.data.id) {
        data.id = this.data.id
        res = await api.updateProductModel(data)
      } else {
        res = await api.createProductModel(data)
      }

      if (res.code === 1) {
        wx.showToast({
          title: this.data.id ? '更新成功' : '创建成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: res.msg || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('保存型号失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  onCancel() {
    wx.navigateBack()
  },

  // 检查是否有权限执行某个操作
  hasPermission(module, action) {
    // 从session中获取管理员信息
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    if (!adminInfo || !adminInfo.id) {
      return false;
    }
    
    // 使用权限工具检查权限（基于管理组）
    return permissionUtils.hasPermission(adminInfo.id, module, action);
  }
})
